package system

import (
	"log"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/google/uuid"
	"go-papers/pkg/lognew"

	"go-papers/models"
	"go-papers/tools"
	"go-papers/tools/app"
)

// @Summary 列表数据
// @Description 获取JSON
// @Tags 用户
// @Param username query string false "username"
// @Success 200 {string} string "{"code": 200, "data": [...]}"
// @Success 200 {string} string "{"code": -1, "message": "抱歉未找到相关信息"}"
// @Router /backend/sysUserList [get]
// @Security Bearer
func GetSysUserList(c *gin.Context) {
	var data models.SysUser
	var err error
	var pageSize = 10
	var pageIndex = 1

	size := c.Request.FormValue("pageSize")
	if size != "" {
		pageSize = tools.StrToInt(err, size)
	}

	index := c.Request.FormValue("pageIndex")
	if index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	data.Username = c.Request.FormValue("username")
	data.NickName = c.Request.FormValue("nickName")
	data.Status = c.Request.FormValue("status")
	data.Phone = c.Request.FormValue("phone")

	postId := c.Request.FormValue("postId")
	data.PostId, _ = tools.StringToInt(postId)

	data.DeptName = c.Request.FormValue("deptName")
	deptId := c.Request.FormValue("deptId")
	data.DeptId, _ = tools.StringToInt(deptId)

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

// GetSysUserOrgan
func GetSysUserOrgan(c *gin.Context) {
	//获取对应类型下的 机构列表
	selectType := c.Request.FormValue("selectUserType")
	if selectType == "" {
		app.CommonResp(c, -1, "参数selectUserType 为空", gin.H{
			"data": selectType,
		})
		return
	}
	// 当前用户属性
	userType := tools.GetUserType(c)
	if userType == "" {
		userType = "1"
	}

	uid := tools.GetUserId(c)
	// 平台
	var organ models.Organ
	result, _ := organ.GetList(uid, userType, selectType)

	app.CommonResp(c, 0, "success", gin.H{
		"data": result,
	})
}

// @Summary 获取用户
// @Description 获取JSON
// @Tags 用户
// @Param userId path int true "用户编码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /backend/sysUser/{userId} [get]
// @Security
func GetSysUser(c *gin.Context) {
	var SysUser models.SysUser
	SysUser.UserId, _ = tools.StringToInt(c.Param("id"))
	result, err := SysUser.Get()
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	var SysRole models.SysRole
	var Post models.Post
	roles, err := SysRole.GetList()
	posts, err := Post.GetList(0)

	postIds := make([]int, 0)
	postIds = append(postIds, result.PostId)

	roleIds := make([]int, 0)
	roleIds = append(roleIds, result.RoleId)
	app.CommonResp(c, 0, "success", gin.H{
		"data":    result,
		"postIds": postIds,
		"roleIds": roleIds,
		"roles":   roles,
		"posts":   posts,
	})
}

// @Summary 获取当前登录用户
// @Description 获取JSON
// @Tags 个人中心
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /backend/user/profile [get]
// @Security
func GetSysUserProfile(c *gin.Context) {
	var SysUser models.SysUser
	userId := tools.GetUserIdStr(c)
	SysUser.UserId, _ = tools.StringToInt(userId)
	result, err := SysUser.Get()
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	var SysRole models.SysRole
	var Post models.Post
	var Dept models.Dept
	//获取角色列表
	roles, err := SysRole.GetList()
	//获取职位列表
	posts, err := Post.GetList(result.DeptId)
	//获取部门列表
	Dept.DeptId = result.DeptId
	dept, err := Dept.Get()

	postIds := make([]int, 0)
	postIds = append(postIds, result.PostId)

	roleIds := make([]int, 0)
	roleIds = append(roleIds, result.RoleId)

	app.CommonResp(c, 0, "success", gin.H{
		"data":    result,
		"postIds": postIds,
		"roleIds": roleIds,
		"roles":   roles,
		"posts":   posts,
		"dept":    dept,
	})
}

// @Summary 获取用户角色和职位
// @Description 获取JSON
// @Tags 用户
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /backend/sysUser [get]
// @Security
func GetSysUserInit(c *gin.Context) {
	var SysRole models.SysRole
	var Post models.Post

	deptId, _ := tools.StringToInt(c.Request.FormValue("deptId"))
	roles, err := SysRole.GetList()
	posts, err := Post.GetList(deptId)
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	mp := make(map[string]interface{}, 2)
	mp["roles"] = roles
	mp["posts"] = posts
	app.OK(c, mp, "")
}

// @Summary 创建用户
// @Description 获取JSON
// @Tags 用户
// @Accept  application/json
// @Product application/json
// @Param data body models.SysUser true "用户数据"
// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /backend/sysUser [post]
func InsertSysUser(c *gin.Context) {
	var sysuser models.SysUser
	err := c.BindWith(&sysuser, binding.JSON)
	tools.HasError(err, "非法数据格式", 500)

	uid := tools.GetUserId(c)
	userInfo, _ := sysuser.GetById(uid)

	uidType := userInfo.UserType

	//平台
	if sysuser.UserType == "1" {
		sysuser.OrganId = 1

	} else if sysuser.UserType == "2" {
		// 达人
		sysuser.OrganId = 2
	} else if sysuser.UserType == "3" {

		// 机构员工 初始化 机构 部门
		if sysuser.OrganId == 0 {
			// 当前用户 机构
			if uidType == "3" {
				sysuser.OrganId = userInfo.OrganId
				sysuser.DeptId = userInfo.DeptId
				sysuser.PostId = userInfo.PostId
				sysuser.DeptName = userInfo.DeptName
			} else {

				// 初始化 默认 机构  默认部门 默认职位
				or := models.Organ{
					OrganName: "[系统默认]机构名称-修改/审核上架课程",
				}
				organInfo, _ := or.Create()
				sysuser.OrganId = organInfo.OrganId
				if organInfo.OrganId > 0 {
					//创建默认 部门 职位
					dep := models.Dept{
						ParentId: 3,
						DeptPath: "",
						DeptName: "总部门",
						DeptDesc: "默认部门",
						DeptNums: 0,
						Sort:     1,
						OrganId:  organInfo.OrganId,
						Status:   "1",
					}
					depInfo, _ := dep.Create()
					sysuser.DeptId = depInfo.DeptId
					//创建职位
					if sysuser.DeptId > 0 {
						pos := models.Post{
							DeptId:   depInfo.DeptId,
							DeptName: "总部门",
							PostName: "管理员",
							PostCode: "DeptAdmin" + tools.IntToString(depInfo.DeptId),
							PostNums: 0,
							Sort:     1,
							Status:   "1",
							Remark:   "系统默认生成",
						}
						posInfo, _ := pos.Create()
						sysuser.PostId = posInfo.PostId
					}
				}

			}

		}

	} else {
		app.ApiResp(c, -1, "用户属性类型位置未知", nil)
		return
	}

	if sysuser.OrganId == 0 {
		app.ApiResp(c, -1, "机构OrganIdd必须填写", nil)
		return
	}

	if sysuser.PostId == 0 {
		app.ApiResp(c, -1, "职位PostId必须填写", nil)
		return
	}
	if sysuser.DeptId == 0 {
		app.ApiResp(c, -1, "部门DeptId必须填写", nil)
		return
	}

	sysuser.RoleId = sysuser.PostId
	sysuser.CreateBy = tools.GetUserIdStr(c)

	lognew.Info(c, "UpdateSysUser", lognew.Fields{"data": sysuser})

	id, err := sysuser.Insert()
	if err != nil {
		app.ApiResp(c, -1, "创建失败："+err.Error(), nil)
		return
	}

	//查询人数
	var depIn models.Dept
	depIn.DeptId = sysuser.DeptId
	depIn.DeptNums, _ = sysuser.GetDeptNums(sysuser.DeptId)
	_, _ = depIn.Update(depIn.DeptId)
	//更新人数
	var postIn models.Post
	postIn.PostId = sysuser.PostId
	postIn.PostNums, _ = sysuser.GetPostNums(sysuser.PostId)
	_, _ = postIn.Update(postIn.PostId)

	app.OK(c, id, "添加成功")
}

// @Summary 修改用户数据
// @Description 获取JSON
// @Tags 用户
// @Accept  application/json
// @Product application/json
// @Param data body models.SysUser true "body"
// @Success 200 {string} string	"{"code": 200, "message": "修改成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "修改失败"}"
// @Router /backend/sysuser/{userId} [put]
func UpdateSysUser(c *gin.Context) {
	var data models.SysUser
	err := c.BindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	if data.PostId == 0 {
		app.ApiResp(c, -1, "职位PostId必须填写", nil)
		return
	}
	if data.DeptId == 0 {
		app.ApiResp(c, -1, "部门DeptId必须填写", nil)
		return
	}

	if data.PostId >= 0 {
		data.RoleId = data.PostId
	}

	lognew.Info(c, "UpdateSysUser", lognew.Fields{"data": data})
	data.UpdateBy = tools.GetUserIdStr(c)
	result, err := data.Update(data.UserId)
	tools.HasError(err, "修改失败", 500)

	//查询人数
	var depIn models.Dept
	depIn.DeptId = result.DeptId
	depIn.DeptNums, _ = data.GetDeptNums(result.DeptId)
	_, _ = depIn.Update(depIn.DeptId)
	//更新人数
	var postIn models.Post
	postIn.PostId = result.PostId
	postIn.PostNums, _ = data.GetPostNums(result.PostId)
	_, _ = postIn.Update(postIn.PostId)

	app.OK(c, result, "修改成功")
}

// @Summary 删除用户数据
// @Description 删除数据
// @Tags 用户
// @Param userId path int true "userId"
// @Success 200 {string} string	"{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "删除失败"}"
// @Router /backend/sysuser/{userId} [delete]
func DeleteSysUser(c *gin.Context) {
	var data models.SysUser
	data.UpdateBy = tools.GetUserIdStr(c)
	IDS := tools.IdsStrToIdsIntGroup("id", c)

	result, err := data.BatchDelete(IDS)
	tools.HasError(err, "删除失败", 500)

	//查询人数
	var depIn models.Dept
	//更新人数
	var postIn models.Post
	dataList := data.GetUidList(IDS)
	for _, v := range dataList {
		depIn.DeptId = v.DeptId
		depIn.DeptNums, _ = data.GetDeptNums(v.DeptId)
		_, _ = depIn.Update(v.DeptId)

		postIn.PostId = v.PostId
		postIn.PostNums, _ = data.GetPostNums(v.PostId)
		_, _ = postIn.Update(v.PostId)
	}

	app.OK(c, result, "删除成功")
}

// @Summary 修改头像
// @Description 获取JSON
// @Tags 用户
// @Accept multipart/form-data
// @Param file formData file true "file"
// @Success 200 {string} string	"{"code": 0, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /backend/user/avatar [post]
func InsetSysUserAvatar(c *gin.Context) {
	form, _ := c.MultipartForm()
	files := form.File["upload[]"]
	guid := uuid.New().String()
	filPath := "static/uploadfile/" + guid + ".jpg"
	for _, file := range files {
		log.Println(file.Filename)
		// 上传文件至指定目录
		_ = c.SaveUploadedFile(file, filPath)
	}
	sysuser := models.SysUser{}
	sysuser.UserId = tools.GetUserId(c)
	sysuser.Avatar = "/" + filPath
	sysuser.UpdateBy = tools.GetUserIdStr(c)
	sysuser.Update(sysuser.UserId)
	app.OK(c, filPath, "修改成功")
}

func SysUserUpdatePwd(c *gin.Context) {
	var pwd models.SysUserPwd
	err := c.Bind(&pwd)
	tools.HasError(err, "数据解析失败", 500)
	sysuser := models.SysUser{}
	sysuser.UserId = tools.GetUserId(c)
	st, err := sysuser.SetPwd(pwd)
	if err != nil {
		app.CommonResp(c, 500, "密码修改失敗", err)
		return
	}
	if st {
		app.CommonResp(c, 0, "密码修改成功", nil)
		return
	}
	app.CommonResp(c, 500, "密码修改失敗", err)
	return
}
